// ================================================
// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [2025-07-28]
// (c) 2020-2025 ALYR.NET // 版权不可修改
// ================================================

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

/**
 * Builder.Alyr.Net 系统健康检查工具
 * @description 检查所有组件和依赖的状态
 */
class SystemHealthChecker {
    constructor() {
        this.results = {
            environment: {},
            dependencies: {},
            files: {},
            services: {},
            overall: 'unknown'
        };
    }

    /**
     * 执行完整的系统健康检查
     */
    async runFullCheck() {
        console.log('🔍 Builder.Alyr.Net 系统健康检查开始...\n');
        
        await this.checkEnvironment();
        await this.checkDependencies();
        await this.checkFiles();
        await this.checkServices();
        
        this.generateReport();
        return this.results;
    }

    /**
     * 检查运行环境
     */
    async checkEnvironment() {
        console.log('📋 [1/4] 检查运行环境...');
        
        try {
            // 检查 Node.js 版本
            const nodeVersion = execSync('node --version', { encoding: 'utf8' }).trim();
            this.results.environment.node = {
                status: 'ok',
                version: nodeVersion,
                message: `Node.js ${nodeVersion} 运行正常`
            };
            console.log(`  ✅ Node.js: ${nodeVersion}`);
        } catch (error) {
            this.results.environment.node = {
                status: 'error',
                message: 'Node.js 未安装或不可用'
            };
            console.log('  ❌ Node.js: 未安装或不可用');
        }

        try {
            // 检查 npm 版本
            const npmVersion = execSync('npm --version', { encoding: 'utf8' }).trim();
            this.results.environment.npm = {
                status: 'ok',
                version: npmVersion,
                message: `npm ${npmVersion} 运行正常`
            };
            console.log(`  ✅ npm: ${npmVersion}`);
        } catch (error) {
            this.results.environment.npm = {
                status: 'error',
                message: 'npm 不可用'
            };
            console.log('  ❌ npm: 不可用');
        }

        // 检查操作系统
        const platform = process.platform;
        this.results.environment.platform = {
            status: 'ok',
            value: platform,
            message: `运行在 ${platform} 平台`
        };
        console.log(`  ✅ 平台: ${platform}`);
        
        console.log('');
    }

    /**
     * 检查项目依赖
     */
    async checkDependencies() {
        console.log('📦 [2/4] 检查项目依赖...');
        
        try {
            // 检查 package.json
            const packagePath = path.join(__dirname, '..', 'config', 'package.json');
            if (fs.existsSync(packagePath)) {
                const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
                this.results.dependencies.package = {
                    status: 'ok',
                    version: packageJson.version,
                    message: `项目版本 ${packageJson.version}`
                };
                console.log(`  ✅ package.json: v${packageJson.version}`);
                
                // 检查关键依赖
                const deps = packageJson.devDependencies || {};
                const requiredDeps = ['chalk', 'chokidar', 'fs-extra'];
                
                for (const dep of requiredDeps) {
                    if (deps[dep]) {
                        console.log(`  ✅ ${dep}: ${deps[dep]}`);
                    } else {
                        console.log(`  ⚠️ ${dep}: 未安装`);
                    }
                }
            } else {
                this.results.dependencies.package = {
                    status: 'error',
                    message: 'package.json 不存在'
                };
                console.log('  ❌ package.json: 不存在');
            }
        } catch (error) {
            this.results.dependencies.package = {
                status: 'error',
                message: `依赖检查失败: ${error.message}`
            };
            console.log(`  ❌ 依赖检查失败: ${error.message}`);
        }
        
        console.log('');
    }

    /**
     * 检查关键文件
     */
    async checkFiles() {
        console.log('📁 [3/4] 检查关键文件...');
        
        // 根据实际目录结构定义关键文件
        const criticalFiles = [
            // core目录文件
            { name: 'ai-rules-checker.js', path: path.join(__dirname, 'ai-rules-checker.js') },
            { name: 'real-time-monitor.js', path: path.join(__dirname, 'real-time-monitor.js') },
            { name: 'auto-fix-helper.js', path: path.join(__dirname, 'auto-fix-helper.js') },
            { name: 'fix-file.js', path: path.join(__dirname, 'fix-file.js') },
            { name: 'start.js', path: path.join(__dirname, 'start.js') },
            
            // utils目录文件
            { name: 'ai-bootstrap.js', path: path.join(__dirname, '..', 'utils', 'ai-bootstrap.js') },
            { name: 'multi-framework-adapter.js', path: path.join(__dirname, '..', 'utils', 'multi-framework-adapter.js') },
            { name: 'code-generator-cli.js', path: path.join(__dirname, '..', 'utils', 'code-generator-cli.js') },
            { name: 'multi-tech-demo.js', path: path.join(__dirname, '..', 'utils', 'multi-tech-demo.js') },
            { name: 'auto-setup.js', path: path.join(__dirname, '..', 'utils', 'auto-setup.js') },
            
            // config目录文件
            { name: 'tech-stack-config.json', path: path.join(__dirname, '..', 'config', 'tech-stack-config.json') },
            { name: 'package.json', path: path.join(__dirname, '..', 'config', 'package.json') }
        ];

        let filesOk = 0;
        let filesTotal = criticalFiles.length;

        for (const fileInfo of criticalFiles) {
            if (fs.existsSync(fileInfo.path)) {
                const stats = fs.statSync(fileInfo.path);
                this.results.files[fileInfo.name] = {
                    status: 'ok',
                    size: stats.size,
                    modified: stats.mtime
                };
                console.log(`  ✅ ${fileInfo.name} (${stats.size} bytes)`);
                filesOk++;
            } else {
                this.results.files[fileInfo.name] = {
                    status: 'missing',
                    message: '文件不存在'
                };
                console.log(`  ❌ ${fileInfo.name}: 文件不存在`);
            }
        }

        this.results.files.summary = {
            total: filesTotal,
            ok: filesOk,
            missing: filesTotal - filesOk,
            percentage: Math.round((filesOk / filesTotal) * 100)
        };

        console.log(`  📊 文件完整性: ${filesOk}/${filesTotal} (${this.results.files.summary.percentage}%)`);
        console.log('');
    }

    /**
     * 检查服务功能
     */
    async checkServices() {
        console.log('⚙️ [4/4] 检查服务功能...');
        
        try {
            // 检查技术栈配置
            const techConfigPath = path.join(__dirname, '..', 'config', 'tech-stack-config.json');
            if (fs.existsSync(techConfigPath)) {
                const techConfig = JSON.parse(fs.readFileSync(techConfigPath, 'utf8'));
                const languageCount = Object.keys(techConfig.languages || {}).length;
                const frameworkCount = Object.keys(techConfig.frameworks || {}).length;
                
                this.results.services.techStack = {
                    status: 'ok',
                    languages: languageCount,
                    frameworks: frameworkCount,
                    message: `支持 ${languageCount} 种语言，${frameworkCount} 个框架`
                };
                console.log(`  ✅ 技术栈配置: ${languageCount} 种语言，${frameworkCount} 个框架`);
            } else {
                this.results.services.techStack = {
                    status: 'error',
                    message: '技术栈配置文件不存在'
                };
                console.log('  ❌ 技术栈配置: 配置文件不存在');
            }

            // 检查代码生成器
            const generatorPath = path.join(__dirname, '..', 'utils', 'code-generator-cli.js');
            if (fs.existsSync(generatorPath)) {
                this.results.services.codeGenerator = {
                    status: 'ok',
                    message: '代码生成器就绪'
                };
                console.log('  ✅ 代码生成器: 就绪');
            } else {
                this.results.services.codeGenerator = {
                    status: 'error',
                    message: '代码生成器不可用'
                };
                console.log('  ❌ 代码生成器: 不可用');
            }

            // 检查智能体规则
            const rulesPath = path.join(__dirname, '..', 'project_rules.md');
            if (fs.existsSync(rulesPath)) {
                this.results.services.aiRules = {
                    status: 'ok',
                    message: '智能体规则已加载'
                };
                console.log('  ✅ 智能体规则: 已加载');
            } else {
                this.results.services.aiRules = {
                    status: 'error',
                    message: '智能体规则文件不存在'
                };
                console.log('  ❌ 智能体规则: 文件不存在');
            }

        } catch (error) {
            console.log(`  ❌ 服务检查失败: ${error.message}`);
        }
        
        console.log('');
    }

    /**
     * 生成检查报告
     */
    generateReport() {
        console.log('📊 系统健康检查报告');
        console.log('========================================');
        
        // 计算总体健康状态
        let totalChecks = 0;
        let passedChecks = 0;
        
        // 统计环境检查
        Object.values(this.results.environment).forEach(check => {
            totalChecks++;
            if (check.status === 'ok') passedChecks++;
        });
        
        // 统计依赖检查
        Object.values(this.results.dependencies).forEach(check => {
            totalChecks++;
            if (check.status === 'ok') passedChecks++;
        });
        
        // 统计服务检查
        Object.values(this.results.services).forEach(check => {
            totalChecks++;
            if (check.status === 'ok') passedChecks++;
        });
        
        // 添加文件完整性
        totalChecks++;
        if (this.results.files.summary && this.results.files.summary.percentage >= 90) {
            passedChecks++;
        }
        
        const healthPercentage = Math.round((passedChecks / totalChecks) * 100);
        
        if (healthPercentage >= 90) {
            this.results.overall = 'excellent';
            console.log('🟢 系统状态: 优秀 (' + healthPercentage + '%)');
        } else if (healthPercentage >= 70) {
            this.results.overall = 'good';
            console.log('🟡 系统状态: 良好 (' + healthPercentage + '%)');
        } else {
            this.results.overall = 'poor';
            console.log('🔴 系统状态: 需要修复 (' + healthPercentage + '%)');
        }
        
        console.log('');
        console.log('💡 建议操作:');
        
        if (this.results.overall === 'excellent') {
            console.log('- ✅ 系统运行良好，可以正常使用所有功能');
            console.log('- 🚀 运行 npm run demo 查看功能演示');
            console.log('- 🛠️ 运行 npm run generate 开始代码生成');
        } else if (this.results.overall === 'good') {
            console.log('- ⚠️ 系统基本正常，建议检查警告项');
            console.log('- 🔧 运行 npm install 重新安装依赖');
        } else {
            console.log('- ❌ 系统存在问题，建议重新安装');
            console.log('- 🔄 运行 one-click-install.bat 重新安装');
        }
        
        console.log('');
        console.log('🔧 技术支持:');
        console.log('- 网站: https://gitee.com/Alyr_space/Builder.Alyr.Net');
        console.log('========================================');
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    const checker = new SystemHealthChecker();
    checker.runFullCheck().catch(console.error);
}

module.exports = SystemHealthChecker;